package sqldb

import (
	_ "github.com/lib/pq"
	"log"
	"github.com/magiconair/properties"
	"github.com/eyediy/dbcontrol"
	"fmt"
)

const (
	DNS_TPL_POSTGRES = `
		host=%s
		dbname=%s
		user=%s
		password=%s
		sslmode=%s
	`
)

// Database .
type Database struct {
	db *dbcontrol.DB
	daoList map[string]*DAO
	// settings
	DebugMode bool
	DefaultLimit int
}

// NewDatabase .
func NewDatabase() *Database {
	return &Database{
		daoList: make(map[string]*DAO),
		DefaultLimit: 200,
	}
}

// LoadPostgres .
// filename - 配置文件
func (m *Database) LoadPostgres(filename string) {
	var (
		err error
	)

	// load properties
	p := properties.MustLoadFile(filename, properties.UTF8)

	// settings
	m.DebugMode = p.GetBool("db.DebugMode", false)
	m.DefaultLimit = p.GetInt("db.DefaultLimit", 100)

	// build connection url
	dsn := fmt.Sprintf(DNS_TPL_POSTGRES,
		p.GetString("db.host",""),
		p.GetString("db.name",""),
		p.GetString("db.user",""),
		p.GetString("db.pass",""),
		p.GetString("sslmode","disable"),
	)

	// open connection
	m.db, err = dbcontrol.Open("postgres",dsn)
	if err != nil {
		log.Fatal(err)
	}
}

func (m *Database) DB() *dbcontrol.DB {
	return m.db
}
